<template>
  <section>
    <!--menu-->
    <el-row style="margin-top: 15px">
      <el-menu :default-active="activeIndex" mode="horizontal" @select="doWhenSelectChanged"
               style="width: 100%">
        <el-submenu index="0">
          <template slot="title">{{menuName}}</template>
          <div v-for="(team,index) in selectorList" :key="index">
            <el-submenu :index="team.teamId + ''" v-if="team.configAppList.length > 0">
              <template slot="title">{{team.teamName}}</template>
              <el-menu-item v-if="team.configAppList.length > 0"
                            v-for="(app,appIndex) in team.configAppList"
                            :index=" team.teamId + '-' + app.appId" :key="appIndex">
                {{app.appName}}
              </el-menu-item>
            </el-submenu>
            <el-menu-item disabled :index="team.teamId + ''" v-else>{{team.teamName}}</el-menu-item>
          </div>
        </el-submenu>
      </el-menu>
    </el-row>

    <el-row style="padding-top: 15px;padding-left: 15px; text-align: center; background-color: #fff">
      <el-col>
        <span style="font-size: 20px; font-family: PingFang SC">{{teamName}} / {{appName}}</span>
      </el-col>
    </el-row>

    <el-row style="padding-top: 15px;padding-left: 15px;background-color: #fff">
      <el-col>
        <el-autocomplete size="small" v-model="state4" :fetch-suggestions="autoCompleteData"
                         popper-class="my-autoComplete" spellcheck="false"
                         placeholder="请输入配置项查询" @select="queryByKey" clearable>
          <template slot-scope="{item}">
            <div class="value">{{ item.value }}</div>
            <span class="keyDes">{{ item.keyDes }}</span>
          </template>
        </el-autocomplete>
        <el-button size="small" type="primary" icon="el-icon-plus" style="margin-left: 10px" @click="configKeyAdd">新增
        </el-button>
        <el-button size="small" type="primary" icon="el-icon-refresh" @click="configKeyHandleSearch">刷新列表
        </el-button>
      </el-col>
    </el-row>


    <el-row style="padding: 25px 15px 15px 15px;background-color: #fff">
      <a-alert style="font-size: 13px"
               message="【实例状态】表示当前注册该配置项的实例，zookeeper上服务器节点的配置项的数据【生效值】与【版本号】与数据库中的是否一致，【正常】则表示一致。"
               type="info" showIcon closeText="关闭"/>
    </el-row>

    <el-row class="el-table-my">
      <el-col>
        <el-table :data="configDataList" fit v-loading="configLoading" style="width: 100%;" stripe
                  header-row-class-name="table-header">
          <el-table-column type="index" label="#"/>
          <el-table-column prop="configKey" label="配置项"/>
          <el-table-column label="生效值">
            <template slot-scope="scope">
              <span>{{scope.row.configValue && scope.row.configValue.substr(0,50)}}</span>
              <el-tooltip v-if="scope.row.configValue &&　scope.row.configValue.length > 50"
                          :content="scope.row.configValue" placement="top" effect="light">
                <span style="cursor: pointer;color: #4a90e2;">...</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="preConfigValue" label="预备值">
            <template slot-scope="scope">
              <span>{{scope.row.preConfigValue && scope.row.preConfigValue.substr(0,50)}}</span>
              <el-tooltip v-if="scope.row.preConfigValue &&　scope.row.preConfigValue.length > 50"
                          :content="scope.row.preConfigValue" placement="top" effect="light">
                <span style="cursor: pointer;color: #4a90e2;">...</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="keyVersion" label="版本号">
            <template slot-scope="scope">
              <el-tag size="small" type="info">{{scope.row.keyVersion}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="tag" label="实例状态" width="300px">
            <template slot-scope="scope">
              <div v-for="item in scope.row.machineNodeDataList" style="padding-top: 5px">
                <!--徽标-->
                <Badge v-if="item.needUpdate === filterData[0].value" status="processing"/>
                <Badge v-if="item.needUpdate === filterData[1].value" status="warning"/>
                <Badge v-if="item.needUpdate === filterData[2].value" status="error"/>
                <!--host-->
                <el-tag size="small" v-if="item.needUpdate === filterData[0].value" type="success">
                  {{item.machineHost}}
                </el-tag>
                <el-tag size="small" v-if="item.needUpdate === filterData[1].value" type="warning">
                  {{item.machineHost}}
                </el-tag>
                <el-tag size="small" v-if="item.needUpdate === filterData[2].value" type="danger">
                  {{item.machineHost}}
                </el-tag>
                <!--生效状态-->
                <el-tag size="small" v-if="item.needUpdate === filterData[0].value" type="success">
                  {{filterData[0].text}}
                </el-tag>
                <el-tag size="small" v-if="item.needUpdate === filterData[1].value" type="warning">
                  {{filterData[1].text}}
                </el-tag>
                <el-tag size="small" v-if="item.needUpdate === filterData[2].value" type="danger">
                  {{filterData[2].text}}
                </el-tag>
              </div>
              <div v-if="scope.row.machineNodeDataList.length === 0" style="padding-top: 5px">
                <el-tag size="small" type="warning">无实例使用</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="keyDes" label="键描述"/>
          <el-table-column label="操作" width="220px">
            <template slot-scope="scope">
              <el-button type="text" size="medium" @click="configKeyEdit(scope.row)">编辑</el-button>
              <Divider type="vertical"/>
              <el-button type="text" size="medium" @click="deleteConfigKey(scope.row)">删除</el-button>
              <Divider type="vertical" v-if="scope.row.preConfigValue || scope.row.pushStatus === 0"/>
              <el-button type="text" size="medium" v-if="scope.row.preConfigValue || scope.row.pushStatus === 0"
                         @click="pushConfigKey(scope.row)">下发
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>

      <!--分页工具条-->
      <el-col :span="24" class="toolbar" style="margin-top: 10px">
        <el-pagination layout="total, sizes, prev, pager, next, jumper" style="float:right;"
                       @size-change="configKeyOnSizeChange"
                       @current-change="configKeyOnPageChange"
                       :page-sizes="[5,10,20]"
                       :current-page.sync="page"
                       :page-count="totalPage"
                       :page-size="size"
                       :total="total">
        </el-pagination>
      </el-col>
    </el-row>

    <!--dialog-->
    <el-dialog :title="configAddOrEditStatus.title" :close-on-click-modal="false"
               width="32%" size="tiny" :visible.sync="configAddOrEditFormVisible">
      <el-form :model="configAddOrEditForm" ref="configAddOrEditForm" label-width="100px">
        <el-form-item label="key" prop="configKey">
          <el-input size="small" v-model="configAddOrEditForm.configKey" auto-complete="off" :disabled="configKeyEnable"
                    placeholder="请填写key" spellcheck="false"/>
        </el-form-item>

        <el-form-item label="生效值" prop="configValue">
          <el-input type="textarea" size="small" v-model="configAddOrEditForm.configValue" rows="5" disabled="true"
                    auto-complete="off"
                    placeholder="请填写预备值" spellcheck="false"/>
        </el-form-item>

        <el-form-item label="预备值" prop="preConfigValue">
          <el-input type="textarea" size="small" v-model="configAddOrEditForm.preConfigValue" rows="5"
                    auto-complete="off"
                    placeholder="请填写预备值" spellcheck="false"/>
        </el-form-item>

        <el-form-item label="版本号" prop="keyVersion">
          <el-input size="small" v-model="configAddOrEditForm.keyVersion" auto-complete="off" :disabled="true"
                    placeholder="由系统自动生成"/>
        </el-form-item>

        <el-form-item label="键描述" prop="keyDes">
          <el-input type="textarea" size="small" v-model="configAddOrEditForm.keyDes" auto-complete="off" rows="3"
                    placeholder="请填写键描述" spellcheck="false"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="configCancel">取 消</el-button>
        <el-button size="mini" type="primary" @click="configAddOrEdit">确 定</el-button>
      </div>
    </el-dialog>


    <!--下发弹窗-->
    <el-dialog title="下发" :close-on-click-modal="false"
               width="32%" size="tiny" :visible.sync="pushFormVisible">

      <el-form :model="pushKeyForm" ref="pushKeyForm" label-width="100px">
        <el-form-item label="key" prop="configKey">
          <el-input size="small" v-model="pushKeyForm.configKey" auto-complete="off" :disabled="true"
                    placeholder="请填写key" spellcheck="false"/>
        </el-form-item>

        <el-form-item label="预备值" prop="preConfigValue">
          <el-input type="textarea" size="small" v-model="pushKeyForm.preConfigValue" rows="5"
                    auto-complete="off" spellcheck="false" :disabled="true"/>
        </el-form-item>
        <div style="color: #FF4949;font-size: 12px;margin-left: 100px;margin-top: -10px;margin-bottom: 20px">
          <p>* 下发时生效值将会被非空的预备值替换, 同时下发到客户端, 请谨慎操作.</p>
          <p>* 在第一次下发的时候, 默认为下发到所有实例, 需要等待实例做出响应.</p>
        </div>
        <el-form-item v-show="showRadio" label="下发策略">
          <RadioGroup v-model="pushType" @on-change="onRadioChanged">
            <Radio label="1">
              <span style="font-size: 13px">全量下发</span>
            </Radio>
            <Radio label="0">
              <span style="font-size: 13px">灰度下发</span>
            </Radio>
          </RadioGroup>
        </el-form-item>

        <el-form-item v-show="showRadio & showSelect" label="选择实例">
          <el-select v-model="selectData" multiple placeholder="请选择实例" size="small">
            <el-option
              v-for="item in machineHostData"
              :key="item.machineHost"
              :label="item.machineHost"
              :value="item.machineHost">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="small" @click="cancelPushConfigKey">取 消</el-button>
        <el-button type="small" @click="confirmPushConfigKey">确 定</el-button>
      </div>
    </el-dialog>


  </section>
</template>

<script>
  import eventBus from '../../common/js/eventBus.js'
  import NProgress from 'nprogress'

  let baseUrL = '/bridge';

  export default {
    data() {
      return {
        appList: {},
        total: 0,
        totalPage: 0,
        size: 10,
        page: 1,
        activeIndex: '0',
        teamName: '',
        appName: '',
        appId: '',
        state4: '',
        pushType: '1',
        clearEnable: true,
        showSelect: false,
        showRadio: false,
        selectData: [],
        configKeyList: [],
        configKey: '',
        menuName: '点击选择系统',
        selectorList: {},
        configAddOrEditForm: {},
        pushKeyForm: {},
        configKeyEnable: false,
        configAddOrEditFormVisible: false,
        pushFormVisible: false,
        configAddOrEditStatus: {
          title: '新增',
          value: 0,
          rules: '',
        },
        filterData: [{text: '正常', value: 0}, {text: '待下发', value: 1}, {text: '未使用', value: 2}],
        configLoading: false,
        configDataList: [],
        machineHostData: [],
      };
    },
    methods: {
      // table数据
      doWhenSelectChanged(tab, event) {
        if (event.length === 3) {
          this.teamId = event[2].split('-')[0];
          this.appId = event[2].split('-')[1];
          localStorage.setItem('teamId', this.teamId);
          localStorage.setItem('appId', this.appId);
          // 查询标签
          this.searchTag();
          // 查询列表数据
          this.searchTab();
        }
      },
      // 根据key查询
      queryByKey(item) {
        this.configKey = item.value;
        // 查询列表数据
        this.searchTab(this.configKey);
      },
      // RadioButton的change事件
      onRadioChanged(val) {
        if (val === '0') {
          this.showSelect = true
        }
        if (val === '1') {
          this.showSelect = false
        }
        this.pushType = val;
        console.log('--------->', val);
      },
      // 在输入框输入数据的时候实时搜索
      autoCompleteData(queryString, cb) {
        if (this.appId) {
          let params = {};
          params.appId = this.appId;
          params.envId = localStorage.getItem('envId');
          let url = baseUrL + '/queryConfigKeyList';
          this.$http.get(url, {params: params}).then(function (res) {
            this.configKeyList = res.body.result;
            let results = queryString ? this.configKeyList.filter(this.createStateFilter(queryString)) : this.configKeyList;
            cb(results);
          }).catch(err => {
            console.log('error', err);
          });
        }
      },

      createStateFilter(queryString) {
        return (state) => {
          return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },

      // 删除
      deleteConfigKey(row) {
        this.$confirm('确认删除该记录吗?', '提示', {type: 'warning'}).then(() => {
          let url = baseUrL + '/deleteConfigKey';
          this.$http.post(url, {id: row.id}, {emulateJSON: true}).then(function (res) {
            if (res.body.success) {
              this.teamAddOrEditFormVisible = false;
              this.$message({showClose: true, message: "操作成功", type: 'success'});
              this.searchTab();
            } else {
              this.$message({showClose: true, message: res.body.message, type: 'error'});
            }
          }).catch((err) => {
            console.log('error', err);
            this.$message({showClose: true, message: err, type: 'error'});
          })
        })
      },

      // 打开下发弹窗
      pushConfigKey(row) {
        this.pushFormVisible = true;
        // 显示编辑页面的默认值
        this.pushKeyForm = {
          configKey: row.configKey,
          preConfigValue: row.preConfigValue,
          keyVersion: row.keyVersion,
          keyDes: row.keyDes,
          id: row.id,
        };
        this.selectData = [];
        this.machineHostData = row.machineNodeDataList;
        if (this.machineHostData.length === 0) {
          this.showRadio = false;
        } else {
          this.showRadio = true;
        }
      },

      // 取消下发
      cancelPushConfigKey() {
        this.pushFormVisible = false;
        this.machineHostData = [];
        this.selectData = [];
        this.$refs['pushKeyForm'].clearValidate();
      },

      // 确认下发
      confirmPushConfigKey() {
        this.pushFormVisible = false;
        let data = this.selectData;
        NProgress.start();
        let params = {};
        let machineLists = '';
        for (let i = 0; i < data.length; i++) {
          machineLists += machineLists ? '&machineList=' + data[i] : 'machineList=' + data[i]
        }
        params.appId = this.appId;
        params.id = this.pushKeyForm.id;
        params.pushType = this.pushType;
        params.envId = localStorage.getItem('envId');
        let url = baseUrL + '/pushConfigKv';
        this.$http.get(url + '?' + machineLists, {params: params}).then(function (res) {
          if (res.body.success) {
            this.$message({showClose: true, message: "操作成功", type: 'success'});
          } else {
            this.$message({showClose: true, message: res.body.message, type: 'error'});
          }
          // 查询列表数据
          this.searchTab();
        }).catch(err => {
          console.log('error', err);
        });
        NProgress.done();
      },

      // 新增或编辑
      configAddOrEdit() {
        if (this.appId.length === 0) {
          this.$message({showClose: true, message: '请选择系统后操作', type: 'error'});
          return false;
        }
        if (!this.configAddOrEditForm.keyDes) {
          this.$message({showClose: true, message: "请输入键的描述", type: 'error'});
          return false;
        }
        if (!this.configAddOrEditForm.configKey) {
          this.$message({showClose: true, message: "请输入key", type: 'error'});
          return false;
        }
        let url;
        if (this.configAddOrEditStatus.value === 0) {
          if (!this.configAddOrEditForm.preConfigValue) {
            this.$message({showClose: true, message: "请输入预备值", type: 'error'});
            return false;
          }
          url = baseUrL + '/addConfigKv';
          this.configAddOrEditForm.envId = localStorage.getItem('envId');
        } else if (this.configAddOrEditStatus.value === 1) {
          url = baseUrL + '/editConfigKv';
        }
        this.configAddOrEditForm.appId = this.appId;
        this.$http.post(url, this.configAddOrEditForm).then(function (res) {
          if (res.body.success) {
            this.configAddOrEditFormVisible = false;
            this.$message({showClose: true, message: "操作成功", type: 'success'});
            this.searchTab();
          } else {
            this.$message({showClose: true, message: res.body.message, type: 'error'});
            this.configAddOrEditFormVisible = true
          }
        }).catch(err => {
          this.$message({showClose: true, message: '表单校验出错', type: 'warning'});
          return false;
        });
      },

      // 取消
      configCancel() {
        this.configAddOrEditFormVisible = false;
        this.$refs['configAddOrEditForm'].clearValidate();
      },

      // 新增
      configKeyAdd() {
        this.configAddOrEditStatus = {
          title: '新增',
          value: 0
        };
        this.configKeyEnable = false;
        this.configAddOrEditFormVisible = true;
        // 显示新增页面的默认值
        this.configAddOrEditForm = {
          configKey: '',
          preConfigValue: '',
          configValue: '',
          keyVersion: '',
          keyDes: '',
          id: '',
          envId: '',
        };
      },

      // 编辑
      configKeyEdit(row) {
        this.configAddOrEditStatus = {
          title: '编辑',
          value: 1
        };
        this.configKeyEnable = true;
        this.configAddOrEditFormVisible = true;
        // 显示编辑页面的默认值
        this.configAddOrEditForm = {
          configKey: row.configKey,
          preConfigValue: row.preConfigValue,
          configValue: row.configValue,
          keyVersion: row.keyVersion,
          keyDes: row.keyDes,
          id: row.id,
          envId: row.envId,
        };
      },

      // 分页
      configKeyOnPageChange(val) {
        this.page = val;
        this.searchTab();
      },
      // 分页
      configKeyOnSizeChange(val) {
        this.size = val;
        this.searchTab();
      },

      // 查询
      configKeyHandleSearch() {
        if (this.appId.length > 0) {
          this.searchTag();
          this.searchTab(this.configKey);
        }
      },

      // 查询标签数据
      searchTag() {
        NProgress.start();
        let url = baseUrL + '/queryTeamNameAndAppNameByAppId';
        let params = {};
        params.appId = this.appId;
        this.$http.get(url, {params: params}).then(function (res) {
          this.teamName = res.body.result.teamName;
          this.appName = res.body.result.appName;
          this.menuName = this.teamName + ' / ' + this.appName;
          localStorage.setItem('teamName', this.teamName);
          localStorage.setItem('appName', this.appName);
          // localStorage.setItem('menuName', this.menuName);
        }).catch(err => {
          console.log('error', err);
        });
        NProgress.done();
      },

      // 查询列表数据
      searchTab(configKey) {
        NProgress.start();
        let params = {};
        params.envId = localStorage.getItem('envId');
        params.appId = this.appId;
        params.page = this.page;
        params.size = this.size;
        if (configKey) {
          params.configKey = configKey;
        }
        let url = baseUrL + '/queryConfigDataByAppId';
        this.$http.get(url, {params: params}).then(function (res) {
          this.configDataList = res.body.result;
          this.total = res.body.total;
          this.totalPage = res.body.totalPage;
        }).catch(err => {
          console.log('error', err);
        });
        NProgress.done();
      },

      // 查询下拉框筛选列表
      getSelectorData() {
        let params = {};
        let url = baseUrL + '/getSelectorData';
        this.$http.get(url, {params: params}).then(function (res) {
          this.selectorList = res.body.result;
        }).catch(err => {
          console.log('error', err);
        });
      }
    },
    mounted() {
      eventBus.$emit('firstColumn', '配置项');
      eventBus.$emit('secondColumn', '配置管理');
      eventBus.$emit('toPage', '/config_manager');
      this.getSelectorData();
      this.teamId = localStorage.getItem('teamId');
      this.appId = localStorage.getItem('appId');
      this.teamName = localStorage.getItem('teamName') ? localStorage.getItem('teamName') : '';
      this.appName = localStorage.getItem('appName') ? localStorage.getItem('appName') : '';
      if (this.appName && this.teamName) {
        this.menuName = this.teamName + ' / ' + this.appName;
      } else {
        this.menuName = '点击选择系统';
      }
      if (this.appId) {
        this.searchTab();
      }
      eventBus.$on('change', () => {
        this.searchTab();
      })
    },
    watch: {
      // 监听输入框，如果没有值并且appId存在则刷新table
      state4(val) {
        if (!val && this.appId.length > 0) {
          this.configKey = val;
          // 查询列表数据
          this.searchTab(this.configKey);
        }
      }
    }
  }
</script>

<style>

  .my-autoComplete li {
    line-height: normal;
    padding: 7px;
  }

  .my-autoComplete li .value {
    text-overflow: ellipsis;
    overflow: hidden;
  }

  .my-autoComplete li .keyDes {
    font-size: 12px;
    color: #b4b4b4;
  }

  .my-autoComplete li .highlighted .keyDes {
    color: #ddd;
  }

</style>
